<?php

namespace app\admin\service;

use app\model\Subject;
use app\model\Company;
// use app\model\Admin;

class SubjectService
{
    private $model;
    private $companyModel;

    public function __construct(Subject $model, Company $companyModel)
    {
        $this->model = $model;
        $this->companyModel = $companyModel;
    }

    // 获取列表数据
    public function getSubjectList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['company_id'])) {
            $where[] = ['company_id', '=', $params['company_id']];
        }
        if (!empty($params['subject'])) {
            $where[] = ['subject', 'like', '%'.$params['subject'].'%'];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit);

        if ($data['data']) {
            $companyIds = array_column($data['data'], 'company_id');
            $companyData = $this->companyModel->getDataByWhere(['id' => $companyIds], 'id, name');
            $company = array_column($companyData, 'name', 'id');

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['company_name'] = empty($company[$value['company_id']]) ? '' : $company[$value['company_id']];
                $data['data'][$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
                switch ($value['media_id']) {
                    case 1:
                        $media = '抖音巨量';
                        break;
                    case 2:
                        $media = '快手磁力';
                        break;
                    case 3:
                        $media = '百度营销';
                        break;
                    case 4:
                        $media = '腾讯广告';
                        break;
                    case 5:
                        $media = '公众号H5';
                        break;
                    case 6:
                        $media = '短信H5';
                        break;
                    case 7:
                        $media = '企业微信';
                        break;
                    default:
                        $media = '未知';
                        break;
                }
                $data['data'][$key]['media'] = $media;
            }
        }

        return $data;
    }

    // 获取详情数据
    public function getSubjectDetail($id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, company_id, media_id, subject, rebate');
        return $data;
    }

    // 添加/编辑
    public function editSubjectData($params, $userInfo)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->model->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }
}